package org.azj.ImageEditor;

import java.io.File;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

import javax.sql.DataSource;

import org.azj.dbOperatorComponent.IDbQueryOperation;
import org.azj.dbOperatorComponent.OperableTable;
import org.azj.dbOperatorComponent.SelectFilter;
import org.azj.logHelper.LOG;
import org.azj.logHelper.LOG_COMPONENT;
import org.azj.logHelper.LOG_LEVEL;
import org.ht.database.BlobToImageHelper;

public class RectifyPatientPrepare extends ImagePreparer {
	private IDbQueryOperation dbOp;
	private DataSource ds;
	private String schema;
	private String tblName;
	private String prepareFilter;
	private String imageColumnName;
	
	// 过滤器的设置方法，例如"ID = '%s'"之类的，在prepare内部会使用String.format()用传入的主题参数替换%s
	public RectifyPatientPrepare(
			DataSource ds, 
			String schema, String tblName, 
			String imageColumnName,
			String prepareFilter) throws Exception{
		this.schema = schema;
		this.tblName = tblName;
		// if column name is not in its full format, append full name
		if (imageColumnName.lastIndexOf(".") == -1) {
			this.imageColumnName = String.format("%s.%s.%s", schema, tblName, imageColumnName);	
		}
		this.prepareFilter = prepareFilter;
		
		// 设置数据库连接
		this.ds = ds;
		try {
			dbOp = new OperableTable(ds, schema, tblName);	
		} catch (SQLException e) {
			String msg = String.format(
					"创建数据表[%s.%s]连接时出现了问题,具体的错误是[%s]", schema, tblName, e.getMessage());
			LOG.WriteLog(
					LOG_LEVEL.INFORMATION, 
					LOG_COMPONENT.LOG_COMP_COMMON, 
					msg);
			throw e;
		}
	}
	
	@Override
	public String prepare(String targetFolder, String filePath) throws Exception{
		File file = new File(filePath);
		String newPath = "";
		
		newPath = String.format("%s\\%s.jpg", targetFolder, filePath.hashCode());
		if (file.exists()) {
			// 如果文件存在，则直接copy过去
			super.copy(filePath, newPath);
		}
		else {
			// filePath所代表的不是一个真实的文件，可能只是数据库中图片的id
			SelectFilter selectFilter = new SelectFilter();
			selectFilter.setWhereFilter(String.format(prepareFilter, filePath));	
	        selectFilter.setColumnList("*");
	        try {
	        	List<HashMap<String, Object>> result = 
		        		dbOp.getSelectCommand(selectFilter).doCommand(ds);
				BlobToImageHelper blobToImgHelper = new BlobToImageHelper();
				blobToImgHelper.writeBlobToFile(
						result.get(0).get(imageColumnName), newPath);
			} catch (Exception e) {
				String msg = String.format(
						"读取数据时出现了问题。源表[%s.%s]出现了问题,具体的错误是[%s]", 
						schema, tblName, e.getMessage());
				LOG.WriteLog(
						LOG_LEVEL.INFORMATION, 
						LOG_COMPONENT.LOG_COMP_COMMON, 
						msg);
				throw new Exception(msg);
			}
		}
		
		return newPath;
	}

}
